<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form label-width="140px" ref="formRef" :model="searchValue">
        <el-row>
          <el-col :span="6">
            <el-form-item label="文件名称" prop="fileName">
              <ns-input v-model="searchValue.fileName" clearable placeholder="请输入文件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文件类型" prop="fileType">
              <ns-input v-model="searchValue.fileType" clearable placeholder="请输入文件类型" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="事件状态" prop="eveStateName">
              <ns-input v-model="searchValue.eveStateName" clearable placeholder="请输入事件状态" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略名称" prop="cmmPnm">
              <ns-input v-model="searchValue.cmmPnm" clearable placeholder="请输入策略名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="组织机构" prop="orgName">
              <ns-input v-model="searchValue.orgName" clearable placeholder="请输入组织机构" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="提交状态" prop="submitStatus">
              <el-select v-model="searchValue.submitStatus" clearable placeholder="请选择提交状态">
                <el-option label="未提交" value="0" />
                <el-option label="已提交" value="1" />
                <!-- <el-option label="已取消" :value="4" /> -->
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="search" type="primary">搜索</el-button>
            <el-button @click="searchReset" plain>重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="openDialog(null)"
          v-hasPermi="['assetList:monitorFile:confirm']"
        >
          提交确认</el-button
        >
        <el-button
          :disabled="ids.length == 0"
          type="danger"
          @click="delList"
          v-hasPermi="['assetList:monitorFile:delete']"
        >
          删除
        </el-button>
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
      <el-dialog :model-value="dialogVisible" v-if="dialogVisible" title="提交确认" @close="cancel">
        <el-form :model="formData" label-width="100px" ref="formDataRef" :rules="rules">
          <el-form-item label="归属机构:" prop="deptId">
            <el-cascader
              ref="deptCascader"
              class="w-100%"
              v-model="formData.deptId"
              placeholder="请选择归属机构"
              :props="cascaderProps"
              :options="deptList"
              filterable
              clearable
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
          <el-form-item label="归属系统:" prop="sysId">
            <el-cascader
              class="w-100%"
              ref="systemCascader"
              v-model="formData.sysId"
              placeholder="请选择归属系统"
              :props="systemCascaderProps"
              :options="systemList"
              filterable
              clearable
              value-on-clear=""
              :filter-method="sysFilterMethod"
            />
          </el-form-item>
          <el-form-item style="margin-bottom: 10px">
            <Icon icon="svg-icon:tips" />
            <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
          </el-form-item>
          <el-form-item label="数据标准:" prop="template" class="col-item">
            <el-select v-model="formData.template" clearable placeholder="请选择数据标准">
              <el-option
                v-for="item in markedTemplateList"
                :label="item.dataStandardName"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="submit" type="primary">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </template>
      </el-dialog>
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import { getDataBaseList, assetDel, assetListDel, monitorAssetEnsure } from '@/api/assetList/index'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { renderFinger } from '@/utils/commonRender'
import { checkPermi } from '@/utils/permission'
import { sysFilterMethod } from '@/utils/selectFilter'
import { handleTree } from '@/utils/tree'
import { getSimpleDeptList } from '@/api/system/dept'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
import { getSimpleSystemList } from '@/api/asset/taskManage'
const tableRef = ref()
const formRef = ref()
const formDataRef = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const ids = ref<string[]>([])

const formData = ref({
  template: '',
  sysId: '',
  deptId: ''
})
const dialogVisible = ref(false)
const markedTemplateList = ref([])
const deptList = ref([])
const systemList = ref([])
const systemCascaderProps = reactive({
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
})
const cascaderProps = reactive({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
})

/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  fileName: '',
  fileType: '',
  eveStateName: '',
  cmmPnm: '',
  orgName: '',
  submitStatus: ''
})

const currentRow = ref<any>(null)
async function getDeptList() {
  const data = await getSimpleDeptList()
  deptList.value = data
}
async function getSystemList() {
  const data = await getSimpleSystemList()
  systemList.value = handleTree(data, 'id', 'pid')
}

const isRequired = computed(() => {
  return !formData.value.deptId && !formData.value.sysId
})
const rules = computed(() => ({
  deptId: [{ required: isRequired.value, message: '归属机构不能为空', trigger: 'change' }],
  sysId: [{ required: isRequired.value, message: '归属系统不能为空', trigger: 'change' }],
  template: [{ required: true, message: '数据标准不能为空', trigger: 'change' }]
}))

const allSelect = ref(false)
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const tableInfo = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: 'id', prop: 'id' },
    { label: '文件名称', width: '100px', prop: 'fileName' },
    { label: '文件类型', width: '100px', prop: 'fileType' },
    { label: '文件大小', width: '100px', prop: 'fileSize' },
    { label: '文件指纹', width: '150px', render: renderFinger },
    { label: '事件状态', width: '100px', prop: 'eveStateName' },
    { label: '策略名称', width: '100px', prop: 'cmmPnm' },
    { label: '组织机构', width: '100px', prop: 'orgName' },
    {
      label: '提交状态',
      width: '100px',
      render: ({ row }) => {
        return <>{row.submitStatus == '1' ? '已提交' : '未提交'}</>
      }
    },
    {
      label: '创建时间',
      width: '180px',
      prop: 'createTime'
    },
    {
      label: '操作项',
      width: '250px',
      render: ({ row }) => {
        return (
          <>
            {row.submitStatus != '1' && checkPermi(['assetList:monitorFile:confirm']) ? (
              <el-button
                link
                type="primary"
                onClick={() => {
                  openDialog(row)
                }}
              >
                提交确认
              </el-button>
            ) : (
              <div></div>
            )}
            {checkPermi(['assetList:monitorFile:delete']) && (
              <ns-button
                style="margin-left:6px"
                link
                type="danger"
                confirm
                onClick={() => {
                  del(row)
                }}
              >
                删除
              </ns-button>
            )}
          </>
        )
      }
    }
  ],
  data: []
})

const del = (row) => {
  proxy?.$modal
    .confirm(`确定要删除该资产吗？`)
    .then(() => {
      assetDel(row.id).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('提交成功')
      })
    })
    .catch(() => {})
}
const delList = () => {
  proxy?.$modal
    .confirm(`确定要删除所选资产吗？`)
    .then(() => {
      assetListDel(ids.value).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {})
}

const pageParams = ref({
  page: 1,
  pageSize: 10
})
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await getDataBaseList({
    page,
    pageSize,
    dataType: 'file',
    isSingle: true,
    source: 5,
    ...searchValue.value
  })
  return { data, count }
}
const openDialog = (row) => {
  dialogVisible.value = true
  currentRow.value = row
}

const submit = async () => {
  const data = await formDataRef.value.validate()
  if (data) {
    //根据currentRow判断是批量还是单次
    const row = [currentRow.value?.id] || ids.value
    submitEnsure(row)
  }
}

const cancel = () => {
  //关闭窗口清空当前数据
  formDataRef.value?.resetFields()
  currentRow.value = null
  dialogVisible.value = false
}
const submitEnsure = (row) => {
  monitorAssetEnsure({
    ids: row,
    ...formData.value,
    deptId: formData.value.deptId || '0'
  }).then((response) => {
    tableRef.value.fetchData()
    ElMessage.success('提交成功')
    cancel()
  })
}
const getStandardsList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 100000, status: '1', type: 0 })
  markedTemplateList.value = data
}

onMounted(() => {
  getSystemList()
  getDeptList()
  getStandardsList()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
